package com.huage.courseplatform.application.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.huage.courseplatform.application.model.dto.BusinessDTO;
import com.huage.courseplatform.application.model.dto.TeacherDTO;
import com.huage.courseplatform.application.model.entity.Business;
import com.huage.courseplatform.application.model.entity.BusinessTeacherFlowRecord;
import com.huage.courseplatform.application.model.entity.Teacher;
import com.huage.courseplatform.application.model.param.AuditPARAM;
import com.huage.courseplatform.application.model.param.BusinessPARAM;
import com.huage.courseplatform.application.model.vo.BusinessTeacherFlowRecordVO;
import com.huage.courseplatform.application.service.BusinessService;
import com.huage.courseplatform.application.service.TeacherService;
import com.huage.courseplatform.framework.annotation.RepeatSubmit;
import com.huage.courseplatform.framework.api.AbstractController;
import com.huage.courseplatform.framework.utils.BeanCopyUtils;
import com.huage.courseplatform.framework.utils.date.LocalDateTimeUtil;
import com.huage.courseplatform.framework.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/business")
@Api(tags = "商户接口")
@Slf4j
public class BusinessController extends AbstractController<Business,BusinessDTO,BusinessPARAM> {

    @Resource
    BusinessService businessService;

    @Resource
    TeacherService teacherService;

    @SaCheckRole({"ROLE_ADMIN","ROLE_BUSINESS"})
    @ApiOperation(value = "根据id查询待审核教师列表")
    @GetMapping(value = "/getTeacherApplyListById/{id}")
    public ResultUtils<List<BusinessTeacherFlowRecordVO>> getTeacherApplyListById(@PathVariable  String id) {
        Assert.isTrue(checkUserBusiness(id),"用户权限不足");

        List<BusinessTeacherFlowRecordVO> teacherApplyList = businessService.getTeacherApplyList(id);

        return ResultUtils.success(teacherApplyList);
    }

    @ApiOperation(value = "根据id查询商家教师列表")
    @GetMapping(value = "/getTeacherListById/{id}")
    public ResultUtils<List<TeacherDTO>> getTeacherListById(@PathVariable  String id) {
        Assert.isTrue(checkUserBusiness(id),"用户权限不足");
        List<Teacher> teachers = teacherService.getTeacherByBusinessId(id);
        List<TeacherDTO> teacherDTOS = BeanCopyUtils.copyWithCollection(teachers,TeacherDTO.class);
        return ResultUtils.success(teacherDTOS);
    }


    @RepeatSubmit
    @SaCheckRole({"ROLE_ADMIN","ROLE_BUSINESS"})
    @ApiOperation(value = "审核教师加入申请")
    @PostMapping(value = "/teacherAudit")
    public ResultUtils<String> teacherAudit(@RequestBody @Validated AuditPARAM auditPARAM) {
        if(auditPARAM.getIsPass()==0){
            Assert.isTrue(StringUtils.isNotEmpty(auditPARAM.getComment()),"不通过的时候，审核意见不能为空");
        }
        BusinessTeacherFlowRecord flowRecord = new BusinessTeacherFlowRecord();
        flowRecord.setId(auditPARAM.getFlowId());
        flowRecord.setWfStatus(auditPARAM.getIsPass());
        flowRecord.setEndTime(LocalDateTimeUtil.parse(LocalDateTime.now()));
        if(StringUtils.isNotEmpty(auditPARAM.getComment())){
            flowRecord.setComment(auditPARAM.getComment());
        }
        businessService.teacherAudit(flowRecord);
        return ResultUtils.success("审核成功");
    }



    @SaCheckRole({"ROLE_ADMIN","ROLE_BUSINESS"})
    @ApiOperation(value = "根据id修改商户信息")
    @PutMapping(value = "/updateByUserId")
    public ResultUtils<BusinessDTO> updateByUserId(@RequestBody @Validated({Update.class}) BusinessPARAM businessPARAM) {
        Assert.isTrue(checkUserBusiness(businessPARAM.getId()),"用户权限不足");
        Business entity = super.paramToEntity(businessPARAM);
        businessService.saveOrUpdate(entity);
        return ResultUtils.success(entityToDto(entity));
    }


    @ApiOperation(value = "根据id查询商户信息")
    @GetMapping(value = "/getById/{id}")
    public ResultUtils<BusinessDTO> getById(@PathVariable String id) {
        Assert.isTrue(checkUserBusiness(id),"用户权限不足");
        return ResultUtils.success(entityToDto( businessService.getById(id)));
    }



    @ApiOperation(value = "根据用户id查询商户信息")
    @GetMapping(value = "/getByUserId/{userId}")
    public ResultUtils<List<BusinessDTO>> getByUserId(@PathVariable String userId) {
        if(!StpUtil.getRoleList().contains("ROLE_ADMIN")){
            //只允许查询本人
            Assert.isTrue(userId.equals(StpUtil.getLoginId()),"用户权限不足");
        }
        List<BusinessDTO> businessDTOList = entityToDto(businessService.getBusinessListByUserId(userId));
        return ResultUtils.success(businessDTOList);
    }

    @ApiOperation(value = "根据用户id获取学生课程相关机构")
    @GetMapping(value = "/getBusinessByUserId/{userId}")
    public ResultUtils<List<BusinessDTO>> getBusinessByUserId(@PathVariable String userId) {
        if(!StpUtil.getRoleList().contains("ROLE_ADMIN")){
            //只允许查询本人
            Assert.isTrue(userId.equals(StpUtil.getLoginId()),"用户权限不足");
        }
        List<BusinessDTO> businessDTOList = entityToDto(businessService.getPeriodBusinessListByUserId(userId));
        return ResultUtils.success(businessDTOList);
    }

    @SaIgnore
    @ApiOperation(value = "获取附近商户")
    @GetMapping(value = "/getBusinessByLocation/{longitude}/{latitude}")
    public ResultUtils<List<BusinessDTO>> getBusinessByLocation(@PathVariable Double longitude,@PathVariable Double latitude) {

        List<BusinessDTO> businessDTOList = entityToDto(businessService.getBusinessByLocation(longitude,latitude));
        return ResultUtils.success(businessDTOList);
    }


    /**
     * 根据商户Id判断当前用户是否存在关联商户
     * @param businessId
     * @return
     */
    private Boolean checkUserBusiness(String businessId){
        if(!StpUtil.getRoleList().contains("ROLE_ADMIN")){
            //只允许修改本人
            String userId = (String) StpUtil.getLoginId();
            List<Business> userBusinessList = businessService.getBusinessListByUserId(userId);
            if(CollectionUtils.isEmpty(userBusinessList)){
                return false;
            }
            //判断商户id是否存在于集合
            Boolean isOwnBusiness = userBusinessList.stream().map(Business::getId).collect(Collectors.toList()).contains(businessId);

            return isOwnBusiness;
        }
        return true;
    }


}
